package com.acxy.cms.service;

import com.acxy.ants.common.enums.DataSourceType;
import com.acxy.ants.common.kit.StrKit;
import com.acxy.ants.core.annotation.Service;
import com.acxy.ants.core.annotation.Source;
import com.acxy.ants.core.annotation.Tx;
import com.acxy.ants.core.exception.TipException;
import com.acxy.ants.core.plugin.db.Db;
import com.acxy.ants.core.plugin.entity.Symbol;
import com.acxy.cms.entity.Category;

import java.util.List;

/**
 * @author MrShun
 * @version 1.0
 * @Date 2017-07-28
 */
@Service
public class CategoryService {

    @Source(DataSourceType.DRUID)
    private Db db;

    public List<Category> queryList(String module) {
        Category category = new Category();
        if (StrKit.notBlank(module)) category.setModule(module);
        List<Category> categorys = category.label("cat_id as catId, cat_name as catName, parent_id as parentId").orderBy("sort", Symbol.ASC).list(db);
        return categorys;
    }

    public List<Category> queryAll(String module) {
        Category category = new Category();
        if (StrKit.notBlank(module)) category.setModule(module);
        List<Category> categorys = category.orderBy("sort", Symbol.ASC).list(db);
        return categorys;
    }

    @Tx
    public int delete(Long[] ids) {
        if (ids == null) throw new TipException("ids 参数不能为空!");
        int res = 0;
        Category category = new Category();
        for (Long id : ids) {
            //根据ID删除分类
            category.deleteById(db, id);
            res++;
        }
        return res;
    }

    public Category find(Long id) {
        return new Category(id).find(db);
    }

    public int save(Category category) {
        Category c = new Category();
        c.setCatDir(category.getCatDir());
        Long count = c.count(db);
        if (count > 0) return -1;
        category.setCount(0L);
        category.setNav(0);
        category.save(db);
        return 1;
    }

    public int update(Category category) {
        Category c = new Category();
        c.setCatDir(category.getCatDir());
        Long count = c.and("catId", "<>", category.getCatId()).count(db);
        if (count > 0) return -1;
        if(category.getSeoKeywords() == null)
            category.setSeoKeywords("");
        if(category.getSeoDescription() == null)
            category.setSeoDescription("");
        return category.update(db);
    }

    public int updateSort(Long id, Integer sort) {
        if (id == null) throw new TipException("id 参数不能为空!");
        Category category = new Category(id);
        category.setSort(sort);
        return category.update(db);
    }

    public int updateNav(Long id, Integer nav) {
        if (id == null) throw new TipException("id 参数不能为空!");
        Category category = new Category(id);
        category.setNav(nav);
        return category.update(db);
    }
}
